package logic

import (
	"context"
	"fmt"
	"module-name/models/cache"
	"module-name/models/mysql"

	"module-name/modulerpc/internal/svc"
	"module-name/modulerpc/modulerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopCarLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopCarLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopCarLogic {
	return &ShopCarLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopCarLogic) ShopCar(in *modulerpc.ShopCarRequest) (*modulerpc.ShopCarResponse, error) {
	// todo: add your logic here and delete this line
	var pro mysql.Product
	err := pro.ProductFind(int(in.ProId))
	if err != nil {
		return nil, fmt.Errorf("该商品不存在，请重新选择")
	}
	if pro.Stock < int(in.Stock) {
		return nil, fmt.Errorf("库存不足,无法加入")
	}
	product := map[string]interface{}{
		"UserId":    in.UserId,
		"ProductId": in.ProId,
		"Name":      pro.Name,
		"Price":     pro.Price,
		"Stock":     in.Stock,
	}
	err = cache.ShopCarAdd(int(in.UserId), int(in.ProId), product)
	if err != nil {
		return nil, fmt.Errorf("添加失败")
	}
	return &modulerpc.ShopCarResponse{
		IsOk:    true,
		Success: "添加成功",
	}, nil
}
